package tools.DNAstar;

import java.io.BufferedReader;
import java.util.Collection;
import java.util.Hashtable;

import tools.utils.DoubleMatrix;

public class MegDM {

	private DoubleMatrix values;
	private Hashtable<String, Integer> names2nr;
	private Hashtable<Integer, String> nr2names;

	public MegDM(BufferedReader in)throws Exception{
		in.readLine();
		in.readLine();
		in.readLine();
		in.readLine();
		in.readLine();
		String header=in.readLine();
//		System.out.println(header);
		String l[]=header.split("\t");
//		System.out.println(l.length);
//		System.out.println("First element in header: <"+l[0]+">");
		names2nr=new Hashtable<String, Integer>();
		nr2names=new Hashtable<Integer, String>();
		values=new DoubleMatrix(l.length,l.length);
		for(int i=1;i<l.length;i++){
//			System.out.println(i+":<"+l[i]+">");
			names2nr.put(l[i], i);
			nr2names.put(i, l[i]);
		}
//		for (String s : names2nr.keySet()) {
//			System.out.println("<"+s+">");
//		}
		for(String s=in.readLine();!s.equals(header);s=in.readLine()){
//			System.out.println(s);
			insert(s);
		}
	}
	
//	public MegDM(String names){
//		String l[]=names.split("\t");
//		names2nr=new Hashtable<String, Integer>();
//		nr2names=new Hashtable<Integer, String>();
//		values=new DoubleMatrix(l.length-1,l.length-1);
//		System.out.println("First element in header: <"+l[0]+">");
//		for(int i=0;i<l.length;i++){
//			names2nr.put(l[0], i);
//			nr2names.put(i, l[i]);
//		}
//	}

	public void insert(String line)throws Exception{
		String l[]=line.split("\t");
		int i=names2nr.get(l[0]);
		for(int j=1;j<l.length-1;j++){
			if(i!=j){
//				System.out.println(j+" "+i+":"+l.length);
//				System.out.println(l[j]);
				values.set(i, j, Double.parseDouble(l[j]));
			}
		}
	}
	
	public double getScore(String x,String y)throws Exception{
		return getScore(names2nr.get(x),names2nr.get(y));
	}
	public double getScore(Integer i,Integer j)throws Exception{
		if(i>j){
			return values.get(i, j);
		}else if(i<j){
			return values.get(j,i);
		}else{
			return 919919.0;
		}
	}
	
	public double getIdentity(String x,String y)throws Exception{
		return getIdentity(names2nr.get(x),names2nr.get(y));
	}
	public double getIdentity(Integer i,Integer j)throws Exception{
		if(i<j){
			return values.get(i, j);
		}else if(i>j){
			return values.get(j,i);
		}else{
			return 100.0;
		}
	}
	
	public Collection<String> getNames(){
		return names2nr.keySet();
	}
}
